
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <fstream>
#include <iostream>

using namespace std;
using namespace cv;

int main(int argc, char *argv[])
{
    string filename = "/home/robot001/frame.raw";

    // open raw data
    std::ifstream fin;
    // 注意，这里要指定binary读取模式
    fin.open(filename,  std::ios::binary);
    if (!fin) {
        std::cerr << "open failed: " << filename << std::endl;
    }

    // seek函数会把标记移动到输入流的结尾
    fin.seekg(0, fin.end);
    // tell会告知整个输入流（从开头到标记）的字节数量
    int length = fin.tellg();
    // 再把标记移动到流的开始位置
    fin.seekg(0, fin.beg);
    std::cout << "file length: " << length << std::endl;

    int w = 3840, h = 2164;

    int frameLen = w*h;

    // load buffer
    char* buffer = new char [frameLen*2];
    uchar *buffer2 = new uchar[frameLen];
    cv::namedWindow("test", WINDOW_NORMAL);
    cv::resizeWindow("test", 1024, 768);
    int count = 0;
    while (fin.read(buffer, frameLen*2)) {
        cout << "===: " << count++ << "read pos: " << fin.tellg() << endl;
        // read函数读取（拷贝）流中的length各字节到buffer
        printf("buffer: %02x %02x %02x %02x\n", buffer[0], buffer[1], buffer[2], buffer[3]);


        for(int i = 0; i< frameLen; i++) {
            buffer2[i] = uchar((buffer[2*i] + ((buffer[2*i+1] & 0x03) << 8)) >> 2);
        }

        printf("buffer2: %02x %02x %02x %02x\n", buffer2[0], buffer2[1], buffer2[2], buffer2[3]);

        // construct opencv mat and show image

        cv::Mat image(h, w, CV_8UC1, buffer2);

        cv::imshow("test", image);
        cv::waitKey();
    }

    delete[] buffer;
    delete[] buffer2;
    fin.close();

    return 0;
}
